/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/idenger">idenger</a> All rights reserved.
 */
package com.idenger.modules.sys.interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.idenger.common.utils.StringUtils;
import com.idenger.common.utils.TokenUtil;
import com.idenger.common.utils.UserAgentUtils;
import com.idenger.common.web.BaseController;
import com.idenger.modules.edu.entity.common.BaseResponseMsg;
import com.idenger.modules.edu.entity.common.ResponseMsg;
import com.idenger.modules.edu.entity.user.UserToken;
import com.idenger.modules.edu.service.user.EduUserService;
import com.idenger.modules.edu.service.user.UserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.idenger.modules.edu.entity.user.EduUser;

/**
 * 手机端视图拦截器
 * @author Idenger
 * @version 2014-9-1
 */
public class MobileInterceptor extends BaseController implements HandlerInterceptor {
	
	@Autowired
	private UserTokenService userTokenService;
	@Autowired
	private EduUserService eduUserService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler) throws Exception {
	//UserTokenService userTokenService = 
		List<String> errorMessageList = new ArrayList<String>();
		BaseResponseMsg baseResponseMsg;
		String tokenId = request.getHeader("tokenId");
		
		logger.info("\n========" + "token id: " + tokenId + "=======\n");
		 if (StringUtils.isEmpty(tokenId)) {
				baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
	            //controller.renderJson("1001", "Token不存在");
				errorMessageList.add("1001,Token不存在");
				baseResponseMsg.addData(errorMessageList);
				renderString(response, baseResponseMsg);
				return false;
	     }
	        // 验证请求tokenId是否有效
	        if (StringUtils.isNotEmpty(tokenId)) {
	            if (TokenUtil.checkTokenId(tokenId) != 1) {
//	              test
	                //controller.renderJson("1011", "Token失效,请重新登录");
	            	baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
	            	errorMessageList.add("1001,Token失效,请重新登录");
					baseResponseMsg.addData(errorMessageList);
					renderString(response, baseResponseMsg);
	                return false;
	            }
	        //    String sql = UserToken.dao.getSql("userToken.getTokenByTokenId");
	          //  UserToken token = UserToken.dao.findFirst(sql,tokenId);
//	              test
	            UserToken token= userTokenService.getTokenByTokenId(tokenId);
//	              test
	            EduUser currentUser = eduUserService.get(token.getUserId());
//	              test
	          //  AuthUser currentUser = AuthUser.dao.findById(token.getUserId());
	            if (currentUser == null) {
	            	// controller.renderJson("1012", "用户不存在");
	            	baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
	            	errorMessageList.add("1001,用户不存在");
					baseResponseMsg.addData(errorMessageList);
					renderString(response, baseResponseMsg);
	                return false;
	            }
	            request.setAttribute("currentUser", currentUser);
	        }
	        baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
	        renderString(response, baseResponseMsg);
	        return true;

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 
			ModelAndView modelAndView) throws Exception {
		if (modelAndView != null){
			// 如果是手机或平板访问的话，则跳转到手机视图页面。
			if(UserAgentUtils.isMobileOrTablet(request) && !StringUtils.startsWithIgnoreCase(modelAndView.getViewName(), "redirect:")){
				modelAndView.setViewName("mobile/" + modelAndView.getViewName());
			}
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
			Object handler, Exception ex) throws Exception {
	}

}
